package com.sfac.hqyj.springBoot.modules.common.controller;


import com.sfac.hqyj.springBoot.modules.common.entity.ExceptionLog;
import com.sfac.hqyj.springBoot.modules.common.service.ExceptionLogService;
import com.sfac.hqyj.springBoot.util.IPUtil;

import com.sfac.hqyj.springBoot.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;

@ControllerAdvice
public class ExceptionHandlerController {

    private final static Logger LOGGER =
            LoggerFactory.getLogger(ExceptionHandlerController.class);
    @Autowired
    private ExceptionLogService exceptionLogService;

    @ExceptionHandler(value = Exception.class)
    public ModelAndView exeptionHandler(HttpServletRequest request, Exception exception) {
        // 异常信息插入数据库
        insertExceptionLog(request, exception);

        /*// 根据请求的方式决定返回的方式
        if (isInterface(request)) {
            return jsonResult(HttpStatus.INTERNAL_SERVER_ERROR.value(),
                    "Internal server error.", "/common/500");
        } else {
            return pageResult("/common/500", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }*/
        String message = "";
        String data = "";
        HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        // 假定 ArithmeticException 为没有权限异常
        if (exception instanceof ArithmeticException) {
            message = "No permit.";
            data = "/common/403";
            httpStatus = HttpStatus.FORBIDDEN;
        } else  {
            message = "Internal server error.";
            data = "/common/500";
            httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        }

        // 根据请求的方式决定返回的方式
        if (isInterface(request)) {
            return jsonResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), message, data);
        } else {
            return pageResult(data, httpStatus);
        }
    }

    public void insertExceptionLog(HttpServletRequest request, Exception ex) {
        ex.printStackTrace();
        LOGGER.debug("======== Log exception into db ========");

        ExceptionLog exceptionLog = new ExceptionLog();
        exceptionLog.setIp(IPUtil.getIpAddr(request));
        exceptionLog.setPath(request.getServletPath());
        HandlerMethod handlerMethod = (HandlerMethod) request.getAttribute(
                "org.springframework.web.servlet.HandlerMapping.bestMatchingHandler");
        if (handlerMethod != null) {
            exceptionLog.setClassName(handlerMethod.getBeanType().getName());
            exceptionLog.setMethodName(handlerMethod.getMethod().getName());
        }
        exceptionLog.setExceptionType(ex.getClass().getSimpleName());
        exceptionLog.setExceptionMessage(StringUtils.isBlank(ex.getMessage()) ? "" :
                StringUtil.splitString(ex.getMessage().trim(), 200));

        exceptionLogService.insertExceptionLog(exceptionLog);
    }

    /**
     * - 根据方法和类上面的注解来判断是否为接口
     */
    public Boolean isInterface(HttpServletRequest request) {
        HandlerMethod handlerMethod = (HandlerMethod) request.getAttribute(
                "org.springframework.web.servlet.HandlerMapping.bestMatchingHandler");
        Annotation[] annotationsForMethod =
                handlerMethod.getMethod().getAnnotationsByType(ResponseBody.class);
        Annotation[] annotationsForClazz =
                handlerMethod.getBeanType().getAnnotationsByType(RestController.class);
        Annotation[] annotationsForClazz2 =
                handlerMethod.getBeanType().getAnnotationsByType(ResponseBody.class);
        return annotationsForMethod.length > 0 ||
                annotationsForClazz.length > 0 ||
                annotationsForClazz2.length > 0;
    }

    /**
     * - 返回错误页面
     */
    public ModelAndView pageResult(String url, HttpStatus httpStatus) {
        return new ModelAndView("redirect:" + url, httpStatus);
    }

    /**
     * - 返回 Json 数据
     */
    public ModelAndView jsonResult(int status, String mesage, Object data) {
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        modelAndView.addObject("status", status);
        modelAndView.addObject("mesage", mesage);
        modelAndView.addObject("data", data);
        return modelAndView;
    }
}